package com.zjut.controller;

import com.zjut.domain.*;
import com.zjut.service.ChapterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.DecimalFormat;
import java.util.List;

@RestController
@RequestMapping("/chapter")
public class ChapterController {
    @Autowired
    private ChapterService chapterService;
    @GetMapping("requirement/{chapter}/{section}")
    public Result getRequirement(@PathVariable int chapter, @PathVariable int section) {
        char requirement = chapterService.getRequirement(chapter,section);
        Integer code = requirement != '\u0000' ? Code.GET_OK : Code.GET_ERR;
        String msg = requirement != '\u0000' ? "" : "数据查询失败，请重试！";
        return new Result(code, requirement, msg);
    }

    @GetMapping("knowledge/{chapter}/{section}")
    public Result getKnowledge(@PathVariable int chapter, @PathVariable int section) {
        String knowledge = chapterService.getKnowledge(chapter,section);
        Integer code = knowledge != null ? Code.GET_OK : Code.GET_ERR;
        String msg = knowledge != null ? "" : "数据查询失败，请重试！";
        return new Result(code, knowledge, msg);
    }

    @PostMapping
    public Result getChapter(@RequestBody Paper paper) {
        DecimalFormat df = new DecimalFormat("#.00");//保留三位小数
        List<Chapter> chapterList = chapterService.getChapter(paper);
        int num = 0;
        for (Chapter c : chapterList){
            if(c.getRequirement()=='a') num+=1;
            if(c.getRequirement()=='b') num+=2;
            if(c.getRequirement()=='c') num+=3;
            if(c.getRequirement()=='d') num+=4;
        }
        for (Chapter c : chapterList){
            if(c.getRequirement()=='a') c.setProportion(Double.valueOf(df.format(1.0/num)));
            if(c.getRequirement()=='b') c.setProportion(Double.valueOf(df.format(2.0/num)));
            if(c.getRequirement()=='c') c.setProportion(Double.valueOf(df.format(3.0/num)));
            if(c.getRequirement()=='d') c.setProportion(Double.valueOf(df.format(4.0/num)));
        }
        Integer code = chapterList != null ? Code.GET_OK : Code.GET_ERR;
        String msg = chapterList != null ? "" : "数据查询失败，请重试！";
        return new Result(code, chapterList, msg);
    }
}
